package com.dragee.modules.work.controller;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dragee.common.PageUtils;
import com.dragee.common.R;
import com.dragee.config.exception.BusinessException;
import com.dragee.config.shiro.NoLogin;
import com.dragee.modules.base.entity.DicEntity;
import com.dragee.modules.base.service.DicService;
import com.dragee.modules.work.dto.*;
import com.dragee.modules.work.entity.*;
import com.dragee.modules.work.service.*;
import com.dragee.modules.work.vo.RefereeInfo;
import com.dragee.modules.work.vo.RefereeSetVo;
import com.dragee.utils.UploadUtil;
import com.dragee.utils.excel.ExcelUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 比赛表
 *
 * @author tc
 * @email tc@mail.com
 * @date 2023-04-24 09:40:38
 */
@RestController
@RequestMapping("work/competition")
@Api(tags = "work - 比赛")
public class CompetitionController {
    @Autowired
    private CompetitionService competitionService;
    @Autowired
    private CompetitionProjectService competitionProjectService;
    @Autowired
    private DicService dicService;
    @Autowired
    private ApplyService applyService;
    @Autowired
    private ApplyProjectService applyProjectService;
    @Autowired
    private TeamRefereeService teamRefereeService;
    @Autowired
    private TeamOtherService teamOtherService;
    @Autowired
    private TeamLeaderService teamLeaderService;
    @Autowired
    private TeamCoachService teamCoachService;
    @Autowired
    private TeamAthleteService teamAthleteService;
    @Autowired
    private TeamService teamService;
    @Autowired
    private CompetitionOrderService competitionOrderService;
    @Autowired
    private CompetitionRefereeService competitionRefereeService;
    @Autowired
    private CompetitionOrderRefereeService competitionOrderRefereeService;
    @Autowired
    private ApplyScoreService applyScoreService;
    @Autowired
    private JdbcTemplate jdbcTemplate;



    /**
     * 列表
     */
    @GetMapping("list")
    @ApiOperation("比赛列表")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = competitionService.queryPage(params);
        return R.ok().put("data", page);
    }
    /**
     * 信息
     */
    @GetMapping("getProjectsByCompetitionId")
    @ApiOperation("获取比赛的项目列表")
    public R getProjects(@RequestParam("competitionId") String competitionId){
        List<CompetitionProjectEntity> projects = competitionProjectService.getProjectByCompetition(competitionId);
        return R.ok().put("data", projects);
    }

    /**
     * 信息 穿梭框数据
     */
    @GetMapping("getApplyProjectByGroupAndProject")
    @ApiOperation("根据组别和项目获取报名比赛项目")
    public R getApplyProjectByGroupAndProject(@RequestParam("competitionId") String competitionId,
                                              String projectId,
                                              String group){
        List<ApplyProjectEntity> aps = new ArrayList<>();
        List<ApplyEntity> applys = applyService.list(new QueryWrapper<ApplyEntity>()
                .eq("competitionId", competitionId)
                .eq("status", "已通过"));
        if (applys.size() == 0) {
            return R.ok().put("data", aps);
        }
        List<Long> applyIds = applys.stream().map(ApplyEntity::getId).collect(Collectors.toList());
        QueryWrapper<ApplyProjectEntity> qw = new QueryWrapper<>();
        qw.in("applyId", applyIds);
        // qw.isNull("status"); // 查看未排序且通过的
        if (StrUtil.isNotBlank(projectId)) {
            qw.eq("projectId", projectId);
        }
        if (StrUtil.isNotBlank(projectId)) {
            qw.eq("groups", group);
        }
        // 排除掉已经排序的
        List<String> finishOrderApplyProjectIds = competitionOrderService.getFinishOrderApplyProjectIds(competitionId);
        if (finishOrderApplyProjectIds.size() > 0) {
            qw.notIn("id", finishOrderApplyProjectIds);
        }
        aps = applyProjectService.list(qw);
        for (ApplyProjectEntity ap : aps) {
            applyService.setApplyProject(ap);
        }
        return R.ok().put("data", aps);
    }

    /**
     * 信息
     */
    @GetMapping("{id}")
    @ApiOperation("比赛详细信息")
    public R info(@PathVariable("id") Long id){
        CompetitionEntity competition = competitionService.getInfoById(id.toString());
        return R.ok().put("data", competition);
    }

    /**
     * 信息
     */
    @GetMapping("getApplySuccessInfo")
    @ApiOperation("获取报名比赛成功的报名信息")
    public R getApplySuccessInfo(@PathVariable("id") Long id){
        List<ApplyEntity> applys = applyService.list(new QueryWrapper<ApplyEntity>()
                .eq("competitionId", id).eq("status", "已通过"));
        List<ApplyEntity> result = new ArrayList<>();
        for (ApplyEntity apply : applys) {
            ApplyEntity applyObj = applyService.getApplyInfo(apply.getId().toString());
            result.add(applyObj);
        }
        return R.ok().put("data", result);
    }

    /**
     * 信息
     */
    @GetMapping("getPersonsOfCompetition")
    @ApiOperation("获取比赛的所有人员信息")
    public R getPersonsOfCompetition(@RequestParam("id") String id){
            List<CompetitionPersonDto> dtos = new ArrayList<>();
        // 获取所有比赛下的报名
        List<ApplyEntity> applys = applyService.list(new QueryWrapper<ApplyEntity>()
                .eq("competitionId", id));
        for (ApplyEntity apply : applys) {
            CompetitionPersonDto cp = new CompetitionPersonDto();
            String teamId = apply.getTeamId();
            TeamEntity team = teamService.getById(teamId);
            cp.setTeamId(teamId);
            cp.setTeamCode(team.getCode());
            cp.setTeamName(team.getName());
            // 设置人员
            String[] coachIds = StrUtil.isNotBlank(apply.getCoachIds())
                    ? apply.getCoachIds().split(",") : new String[]{};
            String[] leaderIds = StrUtil.isNotBlank(apply.getLeaderIds())
                    ? apply.getLeaderIds().split(",") : new String[]{};
            String[] otherIds = StrUtil.isNotBlank(apply.getOtherIds())
                    ? apply.getOtherIds().split(",") : new String[]{};
            String[] refereeIds = StrUtil.isNotBlank(apply.getRefereeIds())
                    ? apply.getRefereeIds().split(",") : new String[]{};
            List<TeamPerson> coachs = new ArrayList<>();
            for (String coachId : coachIds) {
                TeamCoachEntity obj = teamCoachService.getById(coachId);
                coachs.add(new TeamPerson(obj));
            }
            cp.setCoachs(coachs);
            List<TeamPerson> leaders = new ArrayList<>();
            for (String leaderId : leaderIds) {
                TeamLeaderEntity obj = teamLeaderService.getById(leaderId);
                leaders.add(new TeamPerson(obj));
            }
            cp.setLeaders(leaders);
            List<TeamPerson> others = new ArrayList<>();
            for (String otherId : otherIds) {
                TeamOtherEntity obj = teamOtherService.getById(otherId);
                others.add(new TeamPerson(obj));
            }
            cp.setOthers(others);
            List<TeamPerson> referees = new ArrayList<>();
            for (String refereeId : refereeIds) {
                TeamRefereeEntity obj = teamRefereeService.getById(refereeId);
                referees.add(new TeamPerson(obj));
            }
            cp.setReferees(referees);

            List<ProjectInfoAndPerson> projectPersons = new ArrayList<>();
            // 设置项目信息
            List<ApplyProjectEntity> applyPorjects = applyProjectService.list(new QueryWrapper<ApplyProjectEntity>()
                    .eq("applyId", apply.getId()));
            for (ApplyProjectEntity applyPorject : applyPorjects) {
                ProjectInfoAndPerson p = new ProjectInfoAndPerson();
                CompetitionProjectEntity project = competitionProjectService.getById(applyPorject.getProjectId());
                p.setProjectId(applyPorject.getProjectId());
                p.setProjectName(project.getName());
                p.setProjectType(project.getType());
                p.setGroups(applyPorject.getGroups());
                List<TeamPerson> athletes = new ArrayList<>();
                String[] athleteIds = StrUtil.isNotBlank(applyPorject.getAthleteIds())
                        ? applyPorject.getAthleteIds().split(",") : new String[]{};
                for (String athleteId : athleteIds) {
                    TeamAthleteEntity teamAthleteEntity = teamAthleteService.getById(athleteId);
                    athletes.add(new TeamPerson(teamAthleteEntity));
                }
                p.setAthletes(athletes);
                projectPersons.add(p);
            }
            cp.setProjects(projectPersons);
            dtos.add(cp);
        }
        return R.ok().put("data", dtos);
    }

    /**
     * 保存
     */
    @PostMapping("saveOrUpdate")
    @ApiOperation("保存或修改比赛")
    public R saveOrUpdate(@RequestBody CompetitionEntity competition){
        competitionService.saveOrUpdate(competition);

        String groups = competition.getGroups();
        String[] groupArr = groups.split(",");
        for (String s : groupArr) {
            DicEntity dic = dicService.getByChName(s);
            if (dic == null) {
                dic = new DicEntity("group", s);
                dicService.saveOrUpdate(dic);
            }
        }
        return R.ok();
    }
    /**
     * 删除
     */
    @GetMapping("delete-by-id")
    @ApiOperation("比赛删除")
    public R delete( String id){
        deleteCompetitionData(id);
        competitionService.removeById(Long.parseLong(id));
        return R.ok();
    }

    @GetMapping("delete-by-ids")
    @ApiOperation("比赛批量删除")
    public R deletes(String ids){
        String[] idArr = ids.split(",");
        for (String id : idArr) {
            deleteCompetitionData(id);
            competitionService.removeById(Long.parseLong(id));
        }
        return R.ok();
    }


    private void deleteCompetitionData (String id) {
        int total = competitionProjectService.count(new QueryWrapper<CompetitionProjectEntity>().eq("competitionId", id));
        if (total > 0) {
            throw new BusinessException("该比赛下存在比赛项目,请先删除该数据");
        }
        total = applyService.count(new QueryWrapper<ApplyEntity>().eq("competitionId", id));
        if (total > 0) {
            throw new BusinessException("该比赛下存在报名数据,请先删除该数据");
        }
        total = competitionOrderService.count(new QueryWrapper<CompetitionOrderEntity>().eq("competitionId", id));
        if (total > 0) {
            throw new BusinessException("该比赛下存在场次数据,请先删除该数据");
        }
        total = competitionRefereeService.count(new QueryWrapper<CompetitionRefereeEntity>().eq("competitionId", id));
        if (total > 0) {
            throw new BusinessException("该比赛下存在裁判数据,请先删除该数据");
        }
        total = competitionOrderRefereeService.count(new QueryWrapper<CompetitionOrderRefereeEntity>().eq("competitionId", id));
        if (total > 0) {
            throw new BusinessException("该比赛下存在场次裁判数据,请先删除该数据");
        }
        total = applyProjectService.count(new QueryWrapper<ApplyProjectEntity>().eq("competitionId", id));
        if (total > 0) {
            throw new BusinessException("该比赛下存在报名项目,请先删除该数据");
        }
        total = applyScoreService.count(new QueryWrapper<ApplyScoreEntity>().eq("competitionId", id));
        if (total > 0) {
            throw new BusinessException("该比赛下存在报名得分数据,请先删除该数据");
        }

    }



    @ApiOperation(value = "导入项目")
    @PostMapping("project/import")
    public R projectImportData(@RequestParam("file") MultipartFile file,
                        @RequestParam("competitionId") String competitionId) throws IOException {
        if (StrUtil.isBlank(competitionId)) {
            throw new BusinessException("请传入比赛Id");
        }
        return competitionProjectService.importProject(file, competitionId);
    }

    @GetMapping("project/downloadTemplate")
    @ApiOperation(value = "导入项目模板下载", produces = "application/octet-stream")
    @NoLogin
    public void projectDownloadTemplate(HttpServletResponse response) {
        String tempalteName = "导入比赛项目模板";
        String filepath = "static/templates/" + tempalteName + ".xlsx";
        String fileName = tempalteName + ".xlsx";
        UploadUtil.downloadTemplateFromResource(response,filepath,fileName);
    }


    /**
     * 保存
     */
    @PostMapping("project/saveOrUpdate")
    @ApiOperation("保存或修改项目")
    public R saveOrUpdate(@RequestBody CompetitionProjectEntity competitionProject){
        if (StrUtil.isBlank(competitionProject.getCompetitionId())) {
            throw new BusinessException(501, "需要传入比赛的主键");
        }
        if (competitionProject.getEntryPrice() == null) {
            competitionProject.setEntryPrice(BigDecimal.ZERO);
        }
        competitionProjectService.saveOrUpdate(competitionProject);

        // 设置字典
        String projectType = competitionProject.getType();
        DicEntity projectTypeDic = dicService.getByChName(projectType);
        if (projectTypeDic == null) {
            projectTypeDic = new DicEntity("projectType", projectType);
            dicService.saveOrUpdate(projectTypeDic);
        }
        String project = competitionProject.getName();
        String enName = "project-" + projectTypeDic.getId();
        DicEntity projectDic = dicService.getOne(new QueryWrapper<DicEntity>().eq("chName", project).eq("enName", enName), false);
        if (projectDic == null) {
            projectDic = new DicEntity(enName, project);
            dicService.saveOrUpdate(projectDic);
        }
        return R.ok();
    }



    /**
     * 删除
     */
    @GetMapping("project/delete-by-id")
    @ApiOperation("项目删除")
    public R projectDeleteById( String id){
        int total = applyProjectService.count(new QueryWrapper<ApplyProjectEntity>().eq("projectId", id));
        if (total > 0) {
            throw new BusinessException("该数据下存在报名项目数据,请先删除该数据");
        }
        competitionProjectService.removeById(Long.parseLong(id));
        return R.ok();
    }

    /**
     * 信息
     */
    @GetMapping("project/{id}")
    @ApiOperation("项目信息")
    public R projectInfo(@PathVariable("id") Long id){
        CompetitionProjectEntity competition = competitionProjectService.getById(id);
        return R.ok().put("data", competition);
    }






    @GetMapping("getGroupDic")
    @ApiOperation("获取组别Dic")
    public R getGroupDic () {
        List<DicEntity> group = dicService.findDic("group");
        List<String> collect = group.stream().map(DicEntity::getChName).collect(Collectors.toList());
        return R.ok().put("data", collect);
    }

    @GetMapping("getTypeDic")
    @ApiOperation("获取大类Dic")
    public R getTypeDic () {
        List<DicEntity> group = dicService.findDic("projectType");
        List<String> collect = group.stream().map(DicEntity::getChName).collect(Collectors.toList());
        return R.ok().put("data", collect);
    }

    @GetMapping("getProjectDic")
    @ApiOperation("获取小项Dic")
    public R getProjectDic (@RequestParam("type") String type) {
        DicEntity typeDic = dicService.getByChName(type);
        String enName =  "project-" + typeDic.getId();
        List<DicEntity> dic = dicService.findDic(enName);
        List<String> collect = dic.stream().map(DicEntity::getChName).collect(Collectors.toList());
        return R.ok().put("data", collect);
    }


    // =================================================出场顺序=======================================================
    // =================================================出场顺序=======================================================
    // =================================================出场顺序=======================================================

    /**
     * 保存
     */
    @PostMapping("order/saveOrUpdate")
    @ApiOperation("出场顺序--保存或修改")
    public R orderSaveOrUpdate(@RequestBody CompetitionOrderEntity order){
        competitionOrderService.saveOrUpdate(order);
        String applyProjectIds = order.getApplyProjectIds();
        if (StrUtil.isBlank(applyProjectIds)) {
            return R.ok();
        }
        String[] applyProjectArr = applyProjectIds.split(",");
        for (int i = 0; i < applyProjectArr.length; i++) {
            ApplyProjectEntity ap = applyProjectService.getById(applyProjectArr[i]);
            ap.setOrderId(order.getId().toString());
            applyProjectService.saveOrUpdate(ap);
        }
        return R.ok();
    }

    /**
     * 查看出场顺序
     */
    @GetMapping("order/OrderInfo")
    @ApiOperation("出场顺序--根据出场顺序ID查看")
    public R OrderInfo(@RequestParam("id") String id){
        CompetitionOrderEntity order = competitionOrderService.getById(id);
        String applyProjectIds = order.getApplyProjectIds();
        if (StrUtil.isBlank(applyProjectIds)) {
            return R.ok().put("data", order);
        }
        String[] applyProjectArr = applyProjectIds.split(",");
        List<ApplyProjectEntity> applyProjects = new ArrayList<>();
        for (int i = 0; i < applyProjectArr.length; i++) {
            ApplyProjectEntity applyProjectEntity = applyProjectService.getById(applyProjectArr[i]);
            applyService.setApplyProject(applyProjectEntity);
            ApplyScoreEntity score = applyScoreService.getOne(new QueryWrapper<ApplyScoreEntity>().select("score")
                    .eq("applyProjectId", applyProjectArr[i])
                    .eq("orderId", id).eq("type", "裁判长"), false);
            if (score != null) {
                applyProjectEntity.setScore(score.getScore());
            }
            applyProjects.add(applyProjectEntity);
        }
        order.setApplyProjects(applyProjects);
        return R.ok().put("data", order);
    }

    /**
     * 查看出场顺序
     */
    @GetMapping("order/showOrders")
    @ApiOperation("出场顺序--根据比赛ID查看")
    public R showOrders(@RequestParam("id") String id){
        List<CompetitionOrderEntity> orders
                = competitionOrderService.list(new QueryWrapper<CompetitionOrderEntity>().eq("competitionId", id));
        for (CompetitionOrderEntity order : orders) {
            String applyProjectIds = order.getApplyProjectIds();
            if (StrUtil.isBlank(applyProjectIds)) {
                continue;
            }
            String[] applyProjectArr = applyProjectIds.split(",");
            List<ApplyProjectEntity> applyProjects = new ArrayList<>();
            for (int i = 0; i < applyProjectArr.length; i++) {
                ApplyProjectEntity applyProjectEntity = applyProjectService.getById(applyProjectArr[i]);
                applyService.setApplyProject(applyProjectEntity);
                applyProjects.add(applyProjectEntity);
            }
            order.setApplyProjects(applyProjects);
        }
        return R.ok().put("data", orders);
    }


    /**
     * 列表
     */
    @GetMapping("order/list")
    @ApiOperation("出场顺序--列表")
    public R orderList(@RequestParam Map<String, Object> params){
        PageUtils page = competitionOrderService.queryPage(params);
        return R.ok().put("data", page);
    }


    @GetMapping("order/delete-by-id")
    @ApiOperation("出场顺序--删除")
    public R orderDelete(@RequestParam("id") String id){

        int total = applyProjectService.count(new QueryWrapper<ApplyProjectEntity>().eq("orderId", id));
        if (total > 0) {
            throw new BusinessException("该数据下存在报名项目数据,请先删除该数据");
        }
        total = competitionOrderRefereeService.count(new QueryWrapper<CompetitionOrderRefereeEntity>().eq("orderId", id));
        if (total > 0) {
            throw new BusinessException("该数据下存在场次裁判数据,请先删除该数据");
        }
        // 场次表删除
        competitionOrderService.removeById(id);
        // 删除打分表
        applyScoreService.remove(new QueryWrapper<ApplyScoreEntity>().eq("orderId", id));
        return R.ok();
    }



    // ==========================================================================
    // ===================================裁判设置=======================================
    // ==========================================================================


    /**
     * 列表
     */
    @GetMapping("referee/list")
    @ApiOperation("比赛裁判--裁判库列表")
    public R refereeList (@RequestParam Map<String, Object> params) {
        PageUtils page = competitionRefereeService.queryPage(params);
        return R.ok().put("data", page);
    }


    /**
     * 列表
     */
    @PostMapping("referee/set")
    @ApiOperation("比赛裁判--设置裁判")
    public R refereeSet (@RequestBody RefereeSetVo vo) {
        String orderId = vo.getOrderId();
        CompetitionOrderEntity order = competitionOrderService.getById(orderId);
        List<RefereeInfo> referees = vo.getArtisticJudges();
        referees.addAll(vo.getDeputyReferees());
        referees.add(vo.getRefferJudge());
        // 校验身份证号 本场次的身份证号不能存在重复
        long sum = referees.stream().map(RefereeInfo::getIdCard).distinct().count();
        if (sum != referees.size()) {
            throw new BusinessException("本场次裁判存在重复的身份证号，请重新录入");
        }
        // 清除旧数据
        competitionOrderRefereeService.remove(new QueryWrapper<CompetitionOrderRefereeEntity>()
                .eq("orderId", orderId));
        for (RefereeInfo refereeVo : referees) {
            CompetitionOrderRefereeEntity referee = new CompetitionOrderRefereeEntity();
            referee.setName(refereeVo.getName());
            referee.setIdCard(refereeVo.getIdCard());
            referee.setType(refereeVo.getType());
            referee.setOrderId(vo.getOrderId());
            referee.setCompetitionId(order.getCompetitionId());
            referee.setApplyProjectIds(order.getApplyProjectIds());
            competitionOrderRefereeService.saveOrUpdate(referee);
        }
        return R.ok();
    }

    @GetMapping("referee/get")
    @ApiOperation("比赛裁判--获取场次裁判")
    public R refereeSet (@RequestParam("orderId") String orderId) {
        CompetitionOrderEntity order = competitionOrderService.getById(orderId);
        List<CompetitionOrderRefereeEntity> referees = competitionOrderRefereeService.list(new QueryWrapper<CompetitionOrderRefereeEntity>()
                .eq("orderId", orderId));
        RefereeSetVo vo = new RefereeSetVo();
        vo.setOrderId(orderId);
        if (referees.size() == 0) {
            return R.ok().put("data", vo);
        }
        List<RefereeInfo> infos = new ArrayList<>();
        List<RefereeInfo> deputyReferees = new ArrayList<>();
        for (CompetitionOrderRefereeEntity referee : referees) {
            if (referee.getType().equals("裁判长")) {
                vo.setRefferJudge(new RefereeInfo(referee));
            } else if (referee.getType().equals("副裁判长")) {
                deputyReferees.add(new RefereeInfo(referee));
            } else {
                infos.add(new RefereeInfo(referee));
            }
        }
        vo.setArtisticJudges(infos);
        vo.setDeputyReferees(deputyReferees);
        return R.ok().put("data", vo);
    }


    @GetMapping("scoreSort")
    @ApiOperation("分数排名")
    public R scoreSort (@RequestParam("orderId") String orderId) {
        List<ApplyProjectEntity> applyProjects = new ArrayList<>();
        CompetitionOrderEntity order = competitionOrderService.getById(orderId);
        if (order == null) {
            return R.ok().put("data", applyProjects);
        }
        String applyProjectIds = order.getApplyProjectIds();
        String[] applyProjectArr = applyProjectIds.split(",");
        for (int i = 0; i < applyProjectArr.length; i++) {
            ApplyProjectEntity applyProjectEntity = applyProjectService.getById(applyProjectArr[i]);
            applyService.setApplyProject(applyProjectEntity);
            ApplyScoreEntity score = applyScoreService.getOne(new QueryWrapper<ApplyScoreEntity>().select("score")
                    .eq("applyProjectId", applyProjectArr[i])
                    .eq("orderId", orderId).eq("type", "裁判长"), false);
            if (score != null) {
                applyProjectEntity.setScore(score.getScore());
            }
            applyProjects.add(applyProjectEntity);
        }
        // 排序
        applyProjects = applyProjects.stream().sorted((o1, o2) -> {
            BigDecimal o1Score = o1 == null || o1.getScore() == null ? new BigDecimal(0) : o1.getScore();
            BigDecimal o2Score = o2 == null || o2.getScore() == null ? new BigDecimal(0) : o2.getScore();
            return o2Score.compareTo(o1Score);
        }).collect(Collectors.toList());
        return R.ok().put("data", applyProjects);
    }



// ===============================================================================
// ===================================导出========================================
// ===============================================================================

    @ApiOperation(value = "导出缴费信息")
    @GetMapping("/exportPayInfo")
    public void exportPayInfo (@RequestParam("competitionId") String competitionId,
                                HttpServletResponse response ) throws Exception {
        CompetitionEntity competition = competitionService.getById(competitionId);
        List<ApplyEntity> applys = applyService.list(new QueryWrapper<ApplyEntity>()
                .select("id")
                .eq("competitionId", competitionId));
        List<PayInfoExport> datas = new ArrayList<>();
        for (ApplyEntity apply : applys) {
            apply = applyService.getApplyInfo(apply.getId().toString());
            TeamEntity team = teamService.getById(apply.getTeamId());
            PayInfoExport ex = new PayInfoExport();
            ex.setTeamName(team.getName());
            ex.setContactName(team.getContactName());
            ex.setContactTel(team.getContactTel());
            ex.setWaitCost(apply.getCost() + "");
            ex.setFaPiaoShuiHao(apply.getInvoiceTitle());
            ex.setFaPiaoShuiHao(apply.getInvoiceTaxNumber());
            ex.setIsPay(apply.getStatus().equals("已通过") ? "是" : "否");
            datas.add(ex);
        }
        ExcelUtils.writeExcel(response,
                datas,
                competition.getName() + "-缴费信息-" + System.currentTimeMillis(),
                "数据", PayInfoExport.class);
    }

    @ApiOperation(value = "导出参赛单位")
    @GetMapping("/exportApplyUnit")
    public void exportApplyUnit(@RequestParam("competitionId") String competitionId,
                                    HttpServletResponse response ) throws Exception {
        CompetitionEntity competition = competitionService.getById(competitionId);
        List<ApplyEntity> applys = applyService.list(new QueryWrapper<ApplyEntity>()
                .select("teamId")
                .eq("competitionId", competitionId));
        List<TeamExport> datas = new ArrayList<>();
        for (ApplyEntity apply : applys) {
            TeamEntity team = teamService.getById(apply.getTeamId());
            TeamExport ex = new TeamExport();
            ex.setAddress(team.getAddress());
            ex.setCode(team.getCode());
            ex.setContactName(team.getContactName());
            ex.setContactTel(team.getContactTel());
            ex.setName(team.getName());
            datas.add(ex);
        }
        ExcelUtils.writeExcel(response,
                datas,
                competition.getName() + "-报名单位汇总-" + System.currentTimeMillis(),
                "数据", TeamExport.class);
    }

    @ApiOperation(value = "导出随队裁判")
    @GetMapping("/exportFollowReferee")
    public void exportFollowReferee(@RequestParam("competitionId") String competitionId,
                           HttpServletResponse response ) throws Exception {
        CompetitionEntity competition = competitionService.getById(competitionId);
        List<ApplyEntity> applys = applyService.list(new QueryWrapper<ApplyEntity>()
                .select("id")
                .eq("competitionId", competitionId));
        List<TeamPersonExport> datas = new ArrayList<>();
        for (ApplyEntity apply : applys) {
             apply = applyService.getApplyInfo(apply.getId().toString());
            List<TeamPerson> referees = apply.getReferees();
            for (TeamPerson referee : referees) {
                datas.add(new TeamPersonExport(referee, apply.getTeamName()));
            }
        }
        ExcelUtils.writeExcel(response,
                datas,
                competition.getName() + "-随队裁判汇总-" + System.currentTimeMillis(),
                "数据", TeamPersonExport.class);
    }

    @ApiOperation(value = "导出随队人员")
    @GetMapping("/exportFollowOthers")
    public void exportFollowOthers(@RequestParam("competitionId") String competitionId,
                                    HttpServletResponse response ) throws Exception {
        CompetitionEntity competition = competitionService.getById(competitionId);
        List<ApplyEntity> applys = applyService.list(new QueryWrapper<ApplyEntity>()
                .select("id")
                .eq("competitionId", competitionId));
        List<TeamPersonExport> datas = new ArrayList<>();
        for (ApplyEntity apply : applys) {
            apply = applyService.getApplyInfo(apply.getId().toString());
            List<TeamPerson> others = apply.getOthers();
            for (TeamPerson other : others) {
                datas.add(new TeamPersonExport(other, apply.getTeamName()));
            }
        }
        ExcelUtils.writeExcel(response,
                datas,
                competition.getName() + "-随队人员汇总-" + System.currentTimeMillis(),
                "数据", TeamPersonExport.class);
    }

    @ApiOperation(value = "导出运动员")
    @GetMapping("/exportFollowAthlete")
    public void exportFollowAthlete(@RequestParam("competitionId") String competitionId,
                                    HttpServletResponse response ) throws Exception {
        CompetitionEntity competition = competitionService.getById(competitionId);
        List<ApplyEntity> applys = applyService.list(new QueryWrapper<ApplyEntity>()
                .select("id")
                .eq("competitionId", competitionId));
        List<CompetitionAthleteExport> datas = new ArrayList<>();
        for (ApplyEntity apply : applys) {
            apply = applyService.getApplyInfo(apply.getId().toString());
            for (ApplyProjectEntity project : apply.getProjects()) {
                CompetitionAthleteExport ex = new CompetitionAthleteExport();
                ex.setGroups(project.getGroups());
                ex.setName(ArrayUtil.join(project.getAthletes().stream().map(TeamPerson::getName).collect(Collectors.toList()).toArray(), ","));
                ex.setProject(project.getProjectName());
                ex.setTeamName(project.getTeamName());
                ex.setRemark("");
                datas.add(ex);
            }
        }
        datas = datas.stream().sorted(Comparator.comparing(CompetitionAthleteExport::getProject)
                .thenComparing(CompetitionAthleteExport::getGroups)).collect(Collectors.toList());
        ExcelUtils.writeExcel(response,
                datas,
                competition.getName() + "-运动员汇总-" + System.currentTimeMillis(),
                "数据", CompetitionAthleteExport.class);
    }


    @ApiOperation(value = "导出出场顺序")
    @GetMapping("/exportOrderSort")
    public void exportOrderSort(@RequestParam("orderId") String orderId,
                                    HttpServletResponse response ) throws Exception {
        CompetitionOrderEntity order = competitionOrderService.getById(orderId);
        String[] applyProjectIds = order.getApplyProjectIds().split(",");
        List<OrderSortExport> datas = new ArrayList<>();
        for (String applyProjectId : applyProjectIds) {
            OrderSortExport export = new OrderSortExport();
            ApplyProjectEntity applyProject = applyService.getApplyProjectInfo(applyProjectId);
            ApplyEntity apply = applyService.getById(applyProject.getApplyId());
            TeamEntity team = teamService.getById(apply.getTeamId());
            export.setTeamName(team.getName());
            export.setType(applyProject.getType());
            export.setGroups(applyProject.getGroups());
            String athletes = applyProject.getAthletes().stream().map(f -> f.getName()).collect(Collectors.joining(","));
            export.setAthleteName(athletes);
            datas.add(export);
        }
        ExcelUtils.writeExcel(response,
                datas,
                order.getTitle() + "-出场顺序汇总-" + System.currentTimeMillis(),
                "数据", CompetitionAthleteExport.class);
    }
    @GetMapping("demo")
    public String demo () {
        return "success";
    }


    @ApiOperation(value = "出场顺序导入")
    @PostMapping("/importOrderSort")
    public R importOrderSort(@RequestParam("file") MultipartFile file,
                             @RequestParam("orderId") String orderId) throws IOException {
        return competitionService.importData(file, orderId);
    }

    @GetMapping("/downloadTemplate")
    @ApiOperation(value = "出场顺序导入模板下载", produces = "application/octet-stream")
    public void downloadTemplate(HttpServletResponse response) {
        String tempalteName = "导入出场顺序模板";
        String filepath = "static/templates/" + tempalteName + ".xlsx";
        String fileName = tempalteName + ".xlsx";
        UploadUtil.downloadTemplateFromResource(response,filepath,fileName);
    }



}
